#include "results.h"

#include <QMutex>
#include <QMutexLocker>
#include <QDebug>

CResults::CResults()
{
	m_db= QSqlDatabase::addDatabase("QSQLITE");
	m_strDBName = getDBName();
	m_db.setDatabaseName(m_strDBName);
	bool ok = m_db.open();
	if (ok)
	{
        m_db.exec("CREATE TABLE Files (id INTEGER PRIMARY KEY AUTOINCREMENT, name varchar(256) UNIQUE, source TEXT)");
	m_db.exec("CREATE TABLE Plugins (id INTEGER PRIMARY KEY AUTOINCREMENT, name varchar(50) NOT NULL UNIQUE, desc varchar(256) NOT NULL)");
	m_db.exec("CREATE TABLE Results (id INTEGER PRIMARY KEY AUTOINCREMENT, pluginId NUMERIC NOT NULL, fileId NUMERIC NOT NULL, col NUMERIC DEFAULT 0, lineSpan NUMERIC DEFAULT 1, line NUMERIC, severity NUMERIC NOT NULL, code TEXT)");

	if (m_db.driver()->hasFeature(QSqlDriver::LastInsertId))
	{
		qDebug() << "Database supports feature";
	}
	}
}

quint32 CResults::addPlugin(const QString &strName, const QString &strDescription)
{
	QSqlQuery q(QString("INSERT INTO Plugins (name,desc) VALUES('%1','%2')").arg(strName).arg(strDescription), m_db);
	if (q.numRowsAffected() == 1)
	return q.lastInsertId().toUInt();
	return 0;
}

quint32 CResults::addFile(const QString &strFilePath, const QString &strSource)
{
        QSqlQuery q(m_db);
        q.prepare("INSERT INTO Files (name, source) VALUES(?, ?)");
        q.bindValue(0, strFilePath);
        q.bindValue(1, strSource);
        q.exec();

	if (q.numRowsAffected() == 1)
	return q.lastInsertId().toUInt();

	return 0;
}

quint32 CResults::addResult(quint32 nPluginId,
			quint32 nFileId,
			quint32 nLineStart,
			quint32 nCol,
			quint32 nLineEnd,
			quint32 nSeverity,
			const QString &strCode)
{
	QSqlQuery q(QString("INSERT INTO Results (pluginId, fileId, line, col, lineSpan, severity, code) "
			"VALUES (%1, %2, %3, %4, %5, %6, '%7')")
			.arg(nPluginId)
			.arg(nFileId)
			.arg(nLineStart)
			.arg(nCol)
			.arg(nLineEnd)
			.arg(nSeverity)
			.arg(strCode),
		m_db);
	if (q.numRowsAffected() == 1)
	return q.lastInsertId().toUInt();
	return 0;
}

QString CResults::getDBPath()
{
	return m_strDBName;
}

QString CResults::getDBName()
{
	static QMutex m;
	QMutexLocker lock(&m);

	quint32 i = 0;
	QDir d = QDir::temp();
	QString strPath;
	do
	{
	strPath = QString("cpaDB_%1").arg(i++);
	} while (d.exists(strPath));

	return d.absoluteFilePath(strPath);
}

